// src/store/modules/todos.js

// 从 localStorage 读取数据
const loadTodosFromStorage = () => {
  try {
    const serializedState = localStorage.getItem('todos')
    if (serializedState === null) {
      return null // 返回 null 表示没有存储的数据
    }
    return JSON.parse(serializedState)
  } catch (err) {
    console.error('Failed to load todos from localStorage:', err)
    return null // 出错时也返回 null
  }
}

// 保存数据到 localStorage
const saveTodosToStorage = (todos) => {
  try {
    const serializedState = JSON.stringify(todos)
    localStorage.setItem('todos', serializedState)
  } catch (err) {
    console.error('Failed to save todos to localStorage:', err)
  }
}

// 默认数据
const DEFAULT_TODOS = [
  { id: 1, title: '学习 Vue.js', completed: false },
  { id: 2, title: '完成项目', completed: true },
  { id: 3, title: '复习', completed: false }
]

// 定义 todos 模块
const todos = {
  namespaced: true,

  state: {
    todos: loadTodosFromStorage() || DEFAULT_TODOS // 如果 localStorage 为空，使用默认数据
  },

  getters: {
    allTodos: state => state.todos,
    completedTodos: state => state.todos.filter(todo => todo.completed),
    pendingTodos: state => state.todos.filter(todo => !todo.completed)
  },

  mutations: {
    ADD_TODO(state, todo) {
      state.todos.push(todo)
      saveTodosToStorage(state.todos)
    },
    TOGGLE_TODO(state, id) {
      const todo = state.todos.find(t => t.id === id)
      if (todo) {
        todo.completed = !todo.completed
        saveTodosToStorage(state.todos)
      }
    },
    DELETE_TODO(state, id) {
      state.todos = state.todos.filter(t => t.id !== id)
      saveTodosToStorage(state.todos)
    },
    SET_TODOS(state, todos) {
      state.todos = todos
      saveTodosToStorage(state.todos)
    },
    // ✅ 添加清除所有 mutation
    CLEAR_ALL_TODOS(state) {
      state.todos = []
      saveTodosToStorage(state.todos)
    }
  },

  actions: {
    addTodo({ commit }, title) {
      const newTodo = {
        id: Date.now(),
        title: title,
        completed: false
      }
      commit('ADD_TODO', newTodo)
    },
    toggleTodo({ commit }, id) {
      commit('TOGGLE_TODO', id)
    },
    deleteTodo({ commit }, id) {
      commit('DELETE_TODO', id)
    },
    loadTodos({ commit }) {
      const storedTodos = loadTodosFromStorage()
      if (storedTodos !== null) {
        commit('SET_TODOS', storedTodos)
      } else {
        commit('SET_TODOS', DEFAULT_TODOS)
        saveTodosToStorage(DEFAULT_TODOS)
      }
    },
    // ✅ 添加清除所有 action
    clearAllTodos({ commit }) {
      commit('CLEAR_ALL_TODOS')
    }
  }
}

export default todos